﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace ListFileMaker
{
    /// <summary>
    /// Reads all xmk files from the source folder 
    /// and generates a TabsList.xml file on the target location
    /// the list will contain the index of all xml files
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            // Reads the files from the source folder
            // - thus uses source folder from config for source
            // - generates a target file 
            // - uses source folder from config for target
            var conv = new Generator();



            conv.Source = ConfigurationSettings.AppSettings["Source"];
            conv.Target = ConfigurationSettings.AppSettings["Target"];
            conv.MakeFile();

        }
    }

    class Generator
    {
        public string Source { get; set; }
        public string Target { get; set; }
        public void MakeFile()
        {
            var list = new List<TabFile>();
            foreach (string file in Directory.GetFiles(Source, "*.xml"))
            {
                var item = Load<Song>( file);
                list.Add(new TabFile { Name = file.Replace(Source + "\\", ""), Title = item.Title });

                Console.WriteLine(item.Title);
            }

            Save(list, Target);
        }

        public T Load<T>(string fullPath) where T : new()
        {
            T instance;
            if (File.Exists(fullPath))
            {
                string xml = File.ReadAllText(fullPath);
                var serializer = new Serializer<T>();
                instance = serializer.Deserialize(xml);
            }
            else
            {
                instance = new T();
            }

            return instance;
        }

        public void Save<T>(T item, string fullPath)
        {
            // Serialize the current filter instance
            var serializer = new Serializer<T>();
            var xml = serializer.Serialize(item);

            var doc = new XmlDocument();
            doc.LoadXml(xml);
            using (var writer = new XmlTextWriter(fullPath, null))
            {
                writer.Formatting = Formatting.Indented;
                doc.Save(writer);
                writer.Close();
            }
        }
    }

    public class Song
    {
        public string Title { get; set; }
        public string Legend { get; set; }
        public string Content { get; set; }
        public string YouTube { get; set; }
    }
    public class TabFile
    {
        public string Title { get; set; }
        public string Name { get; set; }
    }
}
